<link rel="stylesheet" href="__STATIC_LIB__layuiadmin/layui/layui_ext/dtree/dtree.css">
<link rel="stylesheet" href="__STATIC_LIB__layuiadmin/layui/layui_ext/dtree/font/dtreefont.css">

<form class="layui-form seller-form" lay-filter="deptForm" id="deptForm" action="">
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">部门名称：</label>
            <div class="layui-input-inline">
                <input type="text" id="initstatus" name="initstatus" value = "0" autocomplete="off"
                    class="layui-input layui-hide">
                <input type="text" id="pid" name="pid" value = "1" autocomplete="off"
                    class="layui-input layui-hide">
                <input type="text" id="pname" name="pname" value = "黄河科技学院" autocomplete="off"
                    class="layui-input layui-hide">
                <input id="deptName" type="text" name="deptName" lay-verify="title" placeholder="请输入部门名称" autocomplete="off"
                    class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="*"><i class="iconfont icon-chaxun"></i>筛选</button>
            <button type="button" class="layui-btn layui-btn-sm dept-add"><i class="layui-icon">&#xe608;</i> 添加</button>
        </div>
        <div class="layui-inline">
        </div>
        <div class="layui-inline">
        </div>
    </div>
</form>

<div class="table-body">
    <div class="layui-row layui-col-space10" style="margin-left: 0;">
        <div id="treeContainer" class="layui-col-md3" style="overflow: auto; margin: 15px 0;border-width: 1px; border-style: solid; border-color: #e6e6e6;">
            <tree id="deptTree" class="dtree" data-id="0"></tree>
        </div>
        <div id="tableContainer" class="layui-col-md9">
            <table id="deptTable" lay-filter="deptTable"></table>
        </div>
    </div>
</div> 

<script src="__STATIC_JS__jquery.form.js" type="text/javascript" charset="utf-8"></script>
<script>
    layui.extend({
        dtree: '__STATIC_LIB__layuiadmin/layui/layui_ext/dtree/dtree'
    }).use(['form', 'layedit', 'laydate', 'dtree', 'table'], function () { 
        var layer = layui.layer, table = layui.table,form = layui.form, dtree = layui.dtree;
        // 定义变量保存当前页面和当前页面数据条数
        var currPage; 
        var dataNum;

        table.render({
            elem: '#deptTable',
            height: 'full-115',
            cellMinWidth: '80',
            page: 'true',
            limit: '20',
            url: "{:url('Dept/index')}?_ajax=1&pid=1",
            id: 'deptTable',
            cols: [[
                { type: 'numbers' },
                { field:'id', title:'部门名称', width:280, hide: true },
                { field:'name', title:'部门名称', width:280 },
                { field: 'sort',sort: true, title: '排序', width:80 },
                {
                    field: 'option', title: '操作', templet: function (d) {
                        var html = '';
                        html += '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>';
                        html += '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>';
                        return html;
                    }, align: 'center', width: 120
                }
            ]], //设置表头
            done: function(res, curr, count){
                // 给变量赋值 
                dataNum = res.data.length;
                currPage = curr;
            }
        });

        tree = dtree.render({
            elem: "#deptTree",
            initLevel: 2,
            request:{"id":1},
            url: '{:url("Dept/getList")}',
            checkbar: false,    
            cache: true,
            checkbarType: "all",
            response:{message:"msg",statusCode:0},
            dataStyle: "layuiStyle",
            done: function(res, $ul, first){
                dtree.dataInit("deptTree", $('#pid').val()); 
                if($("#tableContainer").height() > 0) {
                    $("#initstatus").val('1'); 
                }
                $("#treeContainer").height($("#tableContainer").height() - 32);
            }
        });
  
        $(window).resize(function() {
            $("#treeContainer").height($("#tableContainer").height() - 32);
        });　

        //搜索
        form.on('submit(*)', function (data) {
            table.reload('deptTable', {
                where: data.field
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
            
            // 如果有筛选条件则
            // 重置选中节点为根节点 
            if($('#deptName').val() != '') {
                dtree.dataInit("deptTree", '1'); 
                $('#pid').val('1');
                $('#pname').val('黄河科技学院');
            }

            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    
        // 绑定节点点击
        dtree.on("node('deptTree')" ,function(obj){

            // 清理搜索条件
            $('#deptName').val("");
            $('#pid').val(obj.param.nodeId);
            $('#pname').val(obj.param.context);

            table.reload('deptTable', {
                where: {pid: obj.param.nodeId, pname: obj.param.pname, deptName: ''}
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });

            // if(!obj.param.leaf){
            //     var $div = obj.dom;
            //     tree.clickSpread($div);  //调用内置函数展开节点
            // }
        });

        //添加 
        $(document).on('click','.dept-add',function(){
            // 清理搜索条件
            if($('#deptName').val() != '') {
                $('#deptName').val("");
                table.reload('deptTable', {
                    where: {pid: $('#pid').val(), pname: $('#pname').val(), deptName: ''}
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            }

            JsGet("{:url('Dept/add')}?pid="+$('#pid').val()+"&pname="+$('#pname').val(), function(e){
                if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                    layer.msg(e.msg); return false;
                }

                window.box = layer.open({
                    type: 1,
                    content: e,
                    area: ['460px', '385px'],
                    title:'添加部门'
                }); 
            });
            return false;
        });

        //ajax提交商品的添加
        form.on('submit(add-Dept)', function(data){
            if(data.field.deptTreeAdd_select_nodeId == '') {
                layer.msg('请选择上级部门！');
                return;
            }

            if(data.field.name == '') {
                layer.msg('请输入部门名称！');
                return;
            }

            $("#dept_add_save").addClass("layui-btn-disabled");
            $('#dept_add_save').attr("disabled", true);

            // 这里要获取提交的父节点
            $('#pid').val(data.field.deptTreeAdd_select_nodeId);
            $('#pname').val(data.field.deptTreeAdd_select_input);

            JsPost("{:url('Dept/add')}", data.field, function(res){
                if(res.status){
                    layer.close(window.box);
                    layer.msg(res.msg,{time:1300},function(){
                        // 这里需要添加节点后局部刷新
                        layui.dtree.reload('deptTree', {
                            initLevel: 1,
                            done: function(data, obj, first){
                                layui.dtree.dataInit("deptTree", $('#pid').val()); 
                            }
                        });

                        table.reload('deptTable', {
                            where: {pid: $('#pid').val(), pname: $('#pname').val(), deptName: ''}
                            , page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                    });
                }else{
                    $("#dept_add_save").removeClass("layui-btn-disabled");
                    $('#dept_add_save').removeAttr("disabled");

                    layer.msg(res.msg);
                }
            })
        });

        form.on('submit(dept-Edit)',function(data){
            if(data.field.deptTreeAdd_select_nodeId == '') {
                layer.msg('请选择上级部门！');
                return;
            }

            if(data.field.name == '') {
                layer.msg('请输入部门名称！');
                return;
            }

            $("#dept_edit_save").addClass("layui-btn-disabled");
            $('#dept_edit_save').attr("disabled", true);

            // 这里要获取提交的父节点
            $('#pid').val(data.field.deptTreeAdd_select_nodeId);
            $('#pname').val(data.field.deptTreeAdd_select_input);
            
            JsPost("{:url('Dept/edit')}", data.field, function(res){
                if(res.status){
                    layer.close(window.box);
                    layer.msg(res.msg,{time:1300},function(){
                        // 这里需要添加节点后局部刷新
                        layui.dtree.reload('deptTree', {
                            initLevel: 1,
                            done: function(data, obj, first){
                                layui.dtree.dataInit("deptTree", $('#pid').val()); 
                            }
                        });

                        table.reload('deptTable', {
                            where: {pid: $('#pid').val(), pname: $('#pname').val(), deptName: ''}
                            , page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                    });
                }else{
                    $("#dept_edit_save").removeClass("layui-btn-disabled");
                    $('#dept_edit_save').removeAttr("disabled");

                    layer.msg(res.msg,{time:1300});
                }
            })
        });

        //监听工具条
        table.on('tool(deptTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            if(layEvent === 'del'){ //删除
                if(data.id == 1) {
                    layer.msg("一级部门不允许编辑"); return false;
                }

                layer.confirm('真的要删除么',{icon: 3}, function(index){
                    JsPost("{:url('Dept/del')}",{id:data.id}, function (res) {
                        //删除逻辑中判断只有一条数据时应该刷新前一页信息
                        layer.msg(res.msg);
                        if(res.status){
                            if(dataNum == 1){
                                currPage = currPage - 1;
                            }
                            // 这里需要添加节点后局部刷新
                            layui.dtree.reload('deptTree', {
                                initLevel: 1,
                                done: function(data, obj, first){
                                    layui.dtree.dataInit("deptTree", $('#pid').val()); 
                                }
                            });

                            table.reload('deptTable', {
                                page: {
                                    curr: currPage
                                }
                            });
                            return false;
                        }
                    });
                });
            } else if(layEvent === 'edit'){ //编辑
                if(data.id == 1) {
                    layer.msg("一级部门不允许编辑"); return false;
                }

                JsGet("{:url('Dept/edit')}?id=" + data.id + "&pid="+$('#pid').val()+"&pname="+$('#pname').val(), function(e){
                    if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                        layer.msg(e.msg); return false;
                    }
                    
                    window.box = layer.open({
                        type:1,
                        content:e,
                        area: ['460px', '385px'],
                        title:'编辑部门'
                    })
                });
            }
        });
    });
</script>